#include "../inc/urlResolver.h"


urlResolver::urlResolver(){
}

string urlResolver::removeFile(string &src) {

	int ptr = src.length();
	while (src[ptr] != '/')
		ptr--;
	return src.substr(0, ptr) + '/';
}

string urlResolver::removeFolder(string &src) {
	int ptr = src.length();
	int slash = 0;
	while (slash != 2) {
		ptr--;
		if (src[ptr] == '/')
			slash++;
	}
	return src.substr(0, ptr) + "/";
}

int urlResolver::scanString(string *orig, string *rel){
	int pos=0;
	int dotCount = 0;
	while (pos < rel->length()&&!isalnum((*rel)[pos])) {
		if ((*rel)[pos] == '.') {
			dotCount++;
		} else if ((*rel)[pos] == '/') {
			if (dotCount == 2) {
				*orig = removeFolder(*orig);
			} else
				*orig = removeFile(*orig);
			dotCount = 0;
		}
		pos++;
	}
	return pos;
}

string* urlResolver::resolver(string *orig, string *rel) {
	try {
		string resolved("");
		string base(*orig);

		char slash = '/';
		char letter;
		int pos;
		int slashes = 0;

		for (pos = 0; pos < orig->length(); pos++) {//get base URL
			letter = (*orig)[pos];
			if (letter == '/'){
				slashes++;
				if (slashes == 3)
					break;
			}
		}
		base = string(base.substr(0,pos));

		letter = (*rel)[0];
		if (letter == '/') {
			resolved = base.append(*rel);
		} else if (letter == '#') {
			resolved = orig->append(*rel);
		} else {
			pos = 0;

			if (isalnum(letter)) {
				*orig = removeFile(*orig);
			} else
				pos = scanString(orig,rel);
			string temp(rel->substr(pos, rel->length() - pos));
			delete rel;
			rel = new string(temp);
			resolved = orig->append(*rel);

		}
		delete orig;
		delete rel;
		return new string(resolved);
	} catch (...) {
		delete orig;
		delete rel;
		return NULL;
	}
}
